//
//  CartoonDetailsBigTableViewCell.m
//  Cartoon
//
//  Created by dllo on 15/10/31.
//  Copyright © 2015年 YSZ. All rights reserved.
//

#import "CartoonDetailsBigTableViewCell.h"
#import "CartoonDetailsCommentTableViewCell.h"
#import "CartoonDetailsUpdateTableViewCell.h"
#import "CartoonDetailsCollectionViewCell.h"
#import "CartoonDetailsViewController.h"
#import "AlreadyReading.h"



@implementation CartoonDetailsBigTableViewCell



- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        

        
        self.myScrollView = [[UIScrollView alloc] init];
        
        self.myScrollView.delegate = self;
        [self.contentView addSubview:_myScrollView];
        
        self.myCommentTableView = [[UITableView alloc] initWithFrame:self.bounds style:UITableViewStylePlain];
        _myCommentTableView.delegate = self;
        _myCommentTableView.dataSource = self;
        _page = 1;
        _myCommentTableView.footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
            _page ++;
            [self commentHandler];
        }];
        [_myCommentTableView registerClass:[CartoonDetailsCommentTableViewCell class] forCellReuseIdentifier:@"commentCell"];
        [self.myScrollView addSubview:_myCommentTableView];
        _myCommentTableView.allowsSelection = NO;
        
        
        
        self.myUpdateTableView = [[UITableView alloc] initWithFrame:self.bounds style:UITableViewStylePlain];
        _myUpdateTableView.delegate = self;
        _myUpdateTableView.dataSource = self;
        [_myUpdateTableView registerClass:[CartoonDetailsUpdateTableViewCell class] forCellReuseIdentifier:@"updateCell"];
        [self.myScrollView addSubview:_myUpdateTableView];
        self.myUpdateTableView.allowsSelection = NO;
        
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.itemSize = CGSizeMake(self.bounds.size.width / 3 - 20 / WIDTH, 40 * HEIGHT);
        flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        flowLayout.minimumLineSpacing = 20 * WIDTH;
        flowLayout.minimumInteritemSpacing = 20 * WIDTH;
        self.myCollectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:flowLayout];
        _myCollectionView.backgroundColor = [UIColor whiteColor];
        _myCollectionView.bounces = YES;
//        _myCollectionView.pagingEnabled = YES;
        _myCollectionView.delegate = self;
        _myCollectionView.dataSource = self;
        _myCollectionView.showsHorizontalScrollIndicator = NO;
        [self.myScrollView addSubview:_myCollectionView];
        [_myCollectionView registerClass:[CartoonDetailsCollectionViewCell class] forCellWithReuseIdentifier:@"collectionCell"];
        _myCollectionView.contentInset = UIEdgeInsetsMake(40 * HEIGHT, 20 * WIDTH, 20 * HEIGHT, 20 * WIDTH);
        
        self.commentArr = [NSMutableArray array];
 
        
        
        self.updateTimeLabel = [UILabel new];
        _updateTimeLabel.textColor = [UIColor orangeColor];
        _updateTimeLabel.font = [UIFont systemFontOfSize:20];
        _updateTimeLabel.frame = CGRectMake(0, - 30, 80, 20);
        NSString *str = [_model.update_date stringByReplacingOccurrencesOfString:@"-" withString:@"."];
        _updateTimeLabel.text = [str substringToIndex:10];
        [_updateTimeLabel sizeToFit];
        [self.myCollectionView addSubview:_updateTimeLabel];
        
        
        self.cartoonNumLabel = [[UILabel alloc] initWithFrame:CGRectMake(_updateTimeLabel.frame.origin.x + _updateTimeLabel.frame.size.width + 10, _updateTimeLabel.frame.origin.y, 80, 20)];
        self.cartoonNumLabel.frame = CGRectMake(_updateTimeLabel.frame.origin.x + _updateTimeLabel.frame.size.width + 10, _updateTimeLabel.frame.origin.y, 80, 20);
        _cartoonNumLabel.text = [NSString stringWithFormat:@"更新到%@",_model.lastup];
        [_cartoonNumLabel sizeToFit];
        _cartoonNumLabel.font = [UIFont systemFontOfSize:15];
        [self.myCollectionView addSubview:_cartoonNumLabel];
        
        self.upDownButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        _upDownButton.frame = CGRectMake(self.bounds.size.width - 100, - 30, 80, 20);
        _upDownButton.titleLabel.text = @"倒序";
        [_upDownButton setTitle:@"倒序" forState:UIControlStateNormal];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
        imageView.image = [UIImage imageNamed:@"jiantou"];
        [_upDownButton addSubview:imageView];
        _upDownButton.tag = 1000;
        imageView.tag = 1001;
        [_upDownButton addTarget:self action:@selector(upDownButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.myCollectionView addSubview:_upDownButton];
//        _myUpdateTableView.bounces = NO;
//        _myCommentTableView.bounces = NO;
        

    }
    return self;
}
- (void)commentHandler
{
    NSString *str = [NSString stringWithFormat:@"http://mobilev3.ac.qq.com/Comment/commentListV2//comic_id/%@/page/%ld/listcnt/15/uin/0/local_version/3.1.0/channel/1001/guest_id/491A80FA-091B-4330-B939-7DE39BB24F7F",_model.comic_id,_page];
    NSLog(@"%@",_model.comic_id);
    [NetHandler dataWithUrl:str complant:^(id data) {
        NSArray *array = [data objectForKey:@"data"];
        for (NSDictionary *dic in array) {
            CartoonDetailsCommentModel *model = [CartoonDetailsCommentModel new];
            [model setValuesForKeysWithDictionary:dic];
            [self.commentArr addObject:model];
        }
        if (array.count > 0) {
            [self.myCommentTableView.footer endRefreshing];
        }else{
            [self.myCommentTableView.footer endRefreshingWithNoMoreData];
        }
        
        [self.myCommentTableView reloadData];
    }];
}
- (void)layoutSubviews
{
    [super layoutSubviews];
    if (self.commentArr.count == 0) {
        [self commentHandler];
    }
    
    _myScrollView.frame = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
    _myScrollView.contentSize = CGSizeMake(self.bounds.size.width * 3, 0);
    _myScrollView.pagingEnabled = YES;
    _myScrollView.showsHorizontalScrollIndicator = NO;
    
    
    self.myCommentTableView.frame = CGRectMake(self.bounds.size.width * 2, 0, self.bounds.size.width, self.bounds.size.height);
    self.myCollectionView.frame = CGRectMake(self.bounds.size.width, 0, self.bounds.size.width, self.bounds.size.height);
    self.myUpdateTableView.frame = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
    
    _updateTimeLabel.textColor = [UIColor orangeColor];
    _updateTimeLabel.font = [UIFont systemFontOfSize:20];
    _updateTimeLabel.frame = CGRectMake(0, - 30, 80, 20);
    NSString *str = [_model.update_date stringByReplacingOccurrencesOfString:@"-" withString:@"."];
    _updateTimeLabel.text = [str substringToIndex:10];
    [_updateTimeLabel sizeToFit];
    self.cartoonNumLabel.frame = CGRectMake(_updateTimeLabel.frame.origin.x + _updateTimeLabel.frame.size.width + 10, _updateTimeLabel.frame.origin.y, 80, 20);
    _cartoonNumLabel.text = [NSString stringWithFormat:@"更新到%@",_model.lastup];
    [_cartoonNumLabel sizeToFit];
    _cartoonNumLabel.font = [UIFont systemFontOfSize:15];
    
    _upDownButton.frame = CGRectMake(self.bounds.size.width - 100, - 30, 80, 20);
    
    
    [_upDownButton viewWithTag:1001].frame = CGRectMake(0, 0, 20, 20);
    
    

    
}
- (void)upDownButtonAction:(UIButton *)btn
{
    if ([btn.titleLabel.text isEqualToString:@"倒序"]) {
        btn.titleLabel.text = @"正序";
        [btn setTitle:@"正序" forState:UIControlStateNormal];
        [btn viewWithTag:1001].transform = CGAffineTransformMakeRotation(M_PI);
        [_myCollectionView reloadData];
    }else{
        btn.titleLabel.text = @"倒序";
    [btn setTitle:@"倒序" forState:UIControlStateNormal];
    [btn viewWithTag:1001].transform = CGAffineTransformMakeRotation(0);
    
    [_myCollectionView reloadData];
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.myCommentTableView) {
        return self.commentArr.count;
    }else{
        return 4;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.myCommentTableView) {
        CartoonDetailsCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"commentCell"];
        if (_commentArr.count > 0) {
            
        CartoonDetailsCommentModel *model = [self.commentArr objectAtIndex:indexPath.row];
        [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:model.qqhead] placeholderImage:[UIImage imageNamed:@"5"]];
        cell.myNameLabel.text = model.nickName;
        cell.myTimeLabel.text = model.date;
        
        
        cell.myCommentLabel.text = model.content;
        return cell;
        }
        return cell;
    }else{
        CartoonDetailsUpdateTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"updateCell"];
        cell.myAuthorLabel.hidden = YES;
        cell.myAuthorNameLabel.hidden = YES;
        cell.myClassifyLabel1.hidden = YES;
        cell.myClassifyLabel2.hidden = YES;
        cell.myClassifyLabel3.hidden = YES;
        cell.myContentLabel.hidden = YES;
        cell.myImageView.hidden = YES;
        cell.myTitleLabel.hidden = YES;
        cell.myUpdateTimeLabel.hidden = YES;
        switch (indexPath.row) {
            case 0:
                
                [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:self.model.artist_qq_head] placeholderImage:[UIImage imageNamed:@"5"]];
                cell.myImageView.hidden = NO;
                cell.myAuthorLabel.text = @"作者";
                cell.myAuthorLabel.hidden = NO;
                cell.myAuthorNameLabel.text = self.model.artist_name;
                cell.myAuthorNameLabel.hidden = NO;
                return cell;
            
                break;
            case 1:
                
                cell.myTitleLabel.text = @"作品介绍";
                cell.myTitleLabel.hidden = NO;
                cell.myContentLabel.text = self.model.brief_intrd;
                cell.myContentLabel.hidden = NO;
                return cell;
                break;
            case 2:{
                NSArray *typeArray = [_model.type componentsSeparatedByString:@" "];
                cell.myTitleLabel.text = @"作品类型";
                cell.myTitleLabel.hidden  = NO;
                if (typeArray.count > 0) {
                    cell.myClassifyLabel1.text = [typeArray objectAtIndex:0];
                    cell.myClassifyLabel1.hidden = NO;
                }else if (typeArray.count > 1) {
                    cell.myClassifyLabel1.text = [typeArray objectAtIndex:0];
                    cell.myClassifyLabel1.hidden = NO;
                    cell.myClassifyLabel2.text = [typeArray objectAtIndex:1];
                    cell.myClassifyLabel2.hidden = NO;
                }else{
                    cell.myClassifyLabel1.text = [typeArray objectAtIndex:0];
                    cell.myClassifyLabel1.hidden = NO;
                    cell.myClassifyLabel2.text = [typeArray objectAtIndex:1];
                    cell.myClassifyLabel2.hidden = NO;
                    cell.myClassifyLabel3.text = [typeArray objectAtIndex:2];
                    cell.myClassifyLabel3.hidden = NO;
                }

                
                return cell;
            }
                break;
            case 3:{
                NSString *str = [_model.update_date stringByReplacingOccurrencesOfString:@"-" withString:@"."];

                cell.myTitleLabel.text = @"更新时间";
                cell.myTitleLabel.hidden = NO;
                cell.myUpdateTimeLabel.text = [str substringToIndex:10];
                cell.myUpdateTimeLabel.hidden = NO;
                return cell;
            }
                break;
            default:
                break;
        }
    }
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView == _myCommentTableView) {
        UILabel *tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width - 20 - 40 - 10 - 40, 20)];
        CartoonDetailsCommentModel *model = [self.commentArr objectAtIndex:indexPath.row];
        tempLabel.text = model.content;
        tempLabel.numberOfLines = 0;
        [tempLabel sizeToFit];
       
        return 100 > tempLabel.frame.size.height + 100 ? 100 : tempLabel.frame.size.height + 100;
        
    }else{
        if (indexPath.row == 1) {
            UILabel *tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width - 40, 20)];
            tempLabel.text = self.model.brief_intrd;
            tempLabel.numberOfLines = 0;
            [tempLabel sizeToFit];
            
            return 100 > tempLabel.frame.size.height + 80 ? 100 : tempLabel.frame.size.height + 80;
        }
        return 100;
    }
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.myScrollViewDelegate scrollViewDidScroll:scrollView];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [_model.lated_seqno integerValue];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CartoonDetailsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionCell" forIndexPath:indexPath];

    if (self.FMDBarray == nil) {
    
    
    [[FMDB shareFMDB].db open];
    FMResultSet *set = [[FMDB shareFMDB].db executeQuery:@"SELECT * FROM AlreadyReading"];
    self.FMDBarray = [NSMutableArray array];
    
    while ([set next]) {
        
        AlreadyReading *read = [[AlreadyReading alloc]init];
        read.cartoonID = [set stringForColumn:@"cartoonID"];
        read.cartoonPage = [set stringForColumn:@"cartoonPage"];
        if ([[[read.cartoonID componentsSeparatedByString:@"/"] lastObject] isEqualToString:_model.comic_id]) {
            [self.FMDBarray addObject:read];
            break;
        }
    }
        }
    if (self.FMDBarray.count > 0) {
        AlreadyReading *read = self.FMDBarray[0];
        if ([_upDownButton.titleLabel.text isEqualToString:@"倒序"]) {
            if ([[NSString stringWithFormat:@"%ld",indexPath.item + 1] isEqualToString:[[read.cartoonID componentsSeparatedByString:@"/"] firstObject]]) {
                cell.myLabel.layer.borderColor = [[UIColor orangeColor] CGColor];
                cell.myLabel.textColor = [UIColor orangeColor];
            }else{
                cell.myLabel.layer.borderColor = nil;
                cell.myLabel.textColor = nil;
            }
            cell.myLabel.text = [NSString stringWithFormat:@"%ld",indexPath.item + 1];
        }else{
            cell.myLabel.text = [NSString stringWithFormat:@"%ld",[_model.lated_seqno integerValue] - indexPath.item];
            if ([[NSString stringWithFormat:@"%ld",[_model.lated_seqno integerValue] - indexPath.item] isEqualToString:[[read.cartoonID componentsSeparatedByString:@"/"] firstObject]]) {
                cell.myLabel.layer.borderColor = [[UIColor orangeColor] CGColor];
                cell.myLabel.textColor = [UIColor orangeColor];
            }else{
                cell.myLabel.layer.borderColor = nil;
                cell.myLabel.textColor = nil;
            }
            
        }
    }else{
        if ([_upDownButton.titleLabel.text isEqualToString:@"倒序"]) {
            cell.myLabel.text = [NSString stringWithFormat:@"%ld",indexPath.item + 1];
        }else{
            cell.myLabel.text = [NSString stringWithFormat:@"%ld",[_model.lated_seqno integerValue] - indexPath.item];
        }
    }
    
    


    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ([_upDownButton.titleLabel.text isEqualToString:@"正序"]) {
        [self.myCollectionDelegate collectionView:collectionView didSelectItemAtIndexPath:indexPath];
        
    }else{
        NSIndexPath *index = [NSIndexPath indexPathForItem:[_model.lated_seqno integerValue] - indexPath.item - 1 inSection:0];
        
    [self.myCollectionDelegate collectionView:collectionView didSelectItemAtIndexPath:index];
    }
}


- (void)awakeFromNib {
    // Initialization code
  
    
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
